/*
* $Id: BluetoothConnector.java 295 2011-04-05 19:38:33Z volok-aleksej@yandex.ru $
*
* Copyright 2008-2011 by Volokitin Alexey
* All rights reserved
*
*/
package apiary.bt;

import apiary.Apiary;
import apiary.ui.BackScreen;
import java.io.IOException;
import java.util.Vector;
import javax.bluetooth.*;
import javax.bluetooth.ServiceRecord;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.ImageItem;
import javax.microedition.rms.RecordStoreException;

public final class BluetoothConnector extends Form implements DiscoveryListener,
                                                              CommandListener
{
    private Vector m_devices;
    private Vector m_services;
    private DiscoveryAgent agent;
    private Image img;
    private BluetoothSync sync;
    private Command cancel;
    private Command no;
    private Command ok;

    public BluetoothConnector() {
        super(Apiary.getInstance().getLocaleString("SearchDevice"));
        Init();
        append(Apiary.getInstance().getLocaleString("SearchDevice")
               .concat("..."));
        StartScanDevices();
    }
    public BluetoothConnector(RemoteDevice rd) {
        super(Apiary.getInstance().getLocaleString("Synchronize"));
        
        String cancelName = Apiary.getInstance().getLocaleString("Cancel");
        cancel = new Command(cancelName, Command.CANCEL, 1);
        String noName = Apiary.getInstance().getLocaleString("No");
        String okName = Apiary.getInstance().getLocaleString("Yes");
        no = new Command(noName, Command.CANCEL, 1);
        ok = new Command(okName, Command.OK, 2);
        
        Init();
        append(Apiary.getInstance().getLocaleString("Synchronize")
               .concat("..."));
        m_devices.addElement(rd);
        StartScanService(rd);
        setCommandListener(this);
    }

    public Vector getDevices() {
        return m_devices;
    }

    public void deviceDiscovered(RemoteDevice rd, DeviceClass dc) {
        m_devices.addElement(rd);
    }

    public void inquiryCompleted(int i) {
        BackScreen curForm = (BackScreen) Apiary.getInstance().getDisplay();
        Apiary.getInstance().Display(curForm);
        curForm.setData(m_devices);
    }

    public void serviceSearchCompleted(int i, int i1) {
        BackScreen curForm = (BackScreen) Apiary.getInstance().getDisplay();
        try
        {
            if(m_services.isEmpty())
                throw new IOException();
            ServiceRecord record = (ServiceRecord) m_services.elementAt(0);
            String url = record.getConnectionURL(
                    ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
            
            addCommand(cancel);
            
            sync = new BluetoothSync(url);
            sync.outputData();
            sync.inputData();
            
            removeCommand(cancel);
            deleteAll();
            addCommand(ok);
            addCommand(no);
            append(Apiary.getInstance().getLocaleString("QueryInputSync"));
            
        }catch (RecordStoreException ex) {
            Apiary.getInstance().Display(curForm);
        }catch (IOException ex) {
            Apiary.getInstance().Display(curForm);
        }
    }

    public void servicesDiscovered(int i, ServiceRecord[] srs) {
         for(int d = 0; d < srs.length; d++) {
             m_services.addElement(srs[d]);
         }
    }

    private void Init() {
        String logoPath = "/res/Apiary.png";
        try {
            img = Image.createImage(logoPath);
        }
        catch (IOException ioe) {
            System.out.println(ioe.getMessage());
            img = null;
        }
        append(new ImageItem("", img,
               ImageItem.LAYOUT_NEWLINE_AFTER|
               ImageItem.LAYOUT_CENTER,
               logoPath));
        m_devices = new Vector();
        m_services = new Vector();
    }

    private void StartScanDevices() {
        try {
            LocalDevice localDevice = LocalDevice.getLocalDevice();
            agent = localDevice.getDiscoveryAgent();
            agent.startInquiry(DiscoveryAgent.GIAC, this);
        } catch (BluetoothStateException ex) {}
    }

    private void StartScanService(RemoteDevice rd) {
        try {
            UUID[] services = {new UUID(0x1101)};
            int[] args = {0x100};
            LocalDevice localDevice = LocalDevice.getLocalDevice();
            agent = localDevice.getDiscoveryAgent();
            agent.searchServices(args, services, rd, this);
        } catch (BluetoothStateException ex) {}
    }

    public void commandAction(Command c, Displayable d) {
        try {
            if(c.getCommandType() == Command.CANCEL){
                sync.stop();
            }
            if(c.getCommandType() == Command.OK){
                removeCommand(no);
                removeCommand(ok);
                sync.saveData();
            }
        } catch (IOException ex) {
        } catch (RecordStoreException ex) {}
        BackScreen curForm = (BackScreen) Apiary.getInstance().getDisplay();
        Apiary.getInstance().Display(curForm);
    }
}
